package com.wngbms.netty.book._06endec._02;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 *
 *   +------+--------+------+----------------+
 *    | HDR1 | Length | HDR2 | Actual Content |
 *    | 0xCA | 0x0010 | 0xFE | "HELLO, WORLD" |
 *    +------+--------+------+----------------+
 */
@Slf4j
public class CustomerDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        Object value = decode0(in);
        if (value != null) {
            out.add(value);
        } else {
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        }
    }

    private Object decode0(ByteBuf in) {
        // 至关重要
        in.markReaderIndex();
        int readableLength;
        if (in.readableBytes() < 4) {
            log.info("不够4个字节");
            return null;
        }

        byte magic_value = in.readByte();
        log.info("magic value:{}", magic_value);

        short length = in.readShort();
        log.info("content length:{}", length);

        byte version = in.readByte();
        log.info("version:{}", version);

        if ((readableLength = in.readableBytes()) < length) {
            log.info("readableLength is less than length:{} {}", readableLength, length);
            // 至关重要
            in.resetReaderIndex();
            return null;
        }

        byte[] buf = new byte[length];
        in.readBytes(buf);

        return new String(buf, StandardCharsets.UTF_8);
    }

}
